//
//  PhotoTableViewCell.m
//  XPhoto
//
//  Created by baboy on 2019/6/27.
//  Copyright © 2019 baboy. All rights reserved.
//

#import "PhotoTableViewCell.h"
#import <BKKit/BKExt.h>
#import <BKKit/BKUI.h>
#import <AFNetworking/UIButton+AFNetworking.h>
#import "CommonAttributedString.h"
#import "UIButton+tag.h"

#define VIEW_MARGIN 5
#define CONTENT_FONT_SIZE 14


@implementation PhotoTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    self.photoScrollView.scrollLoop = YES;
    self.commentListView.hidden = YES;
    self.likeDescTextView.textContainerInset = UIEdgeInsetsZero;
    self.likeDescTextView.linkTextAttributes = @{};
    self.contentTextView.textContainerInset = UIEdgeInsetsZero;
    self.contentTextView.linkTextAttributes = @{};
    // Initialization code
}
- (void)setStyle:(PhotoTableViewCellStyle)style{
    _style = style;
    self.actionBar.hidden = style == PhotoTableViewCellStyleNoAction;
    self.commentWrapperView.hidden = style == PhotoTableViewCellStyleNoAction;
    [self updateActionBarConstraint];
    [self updateCommentViewConstraint];
}
- (CGRect)contentBounds:(Post *)post{
    CGRect contentBounds = [[CommonAttributedString contentAttributedStringWithPost:post] boundingRectWithSize:CGSizeMake(self.bounds.size.width - 2*self.contentTextView.frame.origin.x, CGFLOAT_MAX)
                                 options:NSStringDrawingUsesLineFragmentOrigin
                                 context:nil];
    return contentBounds;
}
- (void)layoutSubviews1{
//    [super layoutSubviews];
    //photoScrollView frame
    CGRect viewFrame = self.photoScrollView.frame;
    CGFloat y = viewFrame.origin.y;
    viewFrame.size.height = viewFrame.size.width;
    self.photoScrollView.frame = viewFrame;
    y += viewFrame.size.height + VIEW_MARGIN;
    
    //addrBar frame
    viewFrame = self.tagView.frame;
    viewFrame.origin.y = y;
//    viewFrame.size.height = [self.tagView heightWithPost:self.post width:self.bounds.size.width];
    self.tagView.frame = viewFrame;
    y += viewFrame.size.height + VIEW_MARGIN;
    
    
    //actionBar frame
    
    if (self.style == PhotoTableViewCellStyleDefault) {
        viewFrame = self.actionBar.frame;
        viewFrame.origin.y = y;
        self.actionBar.frame = viewFrame;
        y += viewFrame.size.height + VIEW_MARGIN;
    }
    
    //likeDescLabel frame
    self.likeDescTextView.hidden = self.post.likeCount == 0;
    if (!self.likeDescTextView.hidden) {
        viewFrame = self.likeDescTextView.frame;
        viewFrame.origin.y = y;
        self.likeDescTextView.frame = viewFrame;
        y += viewFrame.size.height + VIEW_MARGIN;
    }
    
    //contentLabel frame
    viewFrame = self.contentTextView.frame;
    viewFrame.origin.y = y;
    viewFrame.size.height = ceil([self contentBounds:self.post].size.height);
    self.contentTextView.frame = viewFrame;
    y += viewFrame.size.height + VIEW_MARGIN;
    
    
    viewFrame = self.timeLabel.frame;
    viewFrame.origin.y = y;
    self.timeLabel.frame = viewFrame;
    y += viewFrame.size.height + VIEW_MARGIN;
    
    viewFrame = self.commentWrapperView.frame;
    viewFrame.origin.y = y;
    self.commentWrapperView.frame = viewFrame;
    y += viewFrame.size.height + VIEW_MARGIN;
    
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    // Configure the view for the selected state
}
- (NSArray *)photoItems:(Post *)post{
    NSMutableArray *arr = [NSMutableArray arrayWithCapacity:post.items.count];
    for (NSInteger i = 0; i < post.items.count; i++) {
        PostItem * item = [post.items objectAtIndex:i];
        BKPhotoItem *photoItem = [BKPhotoItem new];
        photoItem.type = item.type;
        photoItem.thumb = item.thumb;
        photoItem.url = item.url;
        [arr addObject:photoItem];
    }
    return arr;
}
- (void)updateTagViewConstraint{
    [self.tagView clear];
    if (self.post.serials) {
        for (NSInteger i = 0, n = self.post.serials.count; i < n; i++) {
            PostSerial *serial = [self.post.serials objectAtIndex:i];
            [self.tagView addTag:serial.title type:TagButtonTypeSerial userInfo:@{@"type":@(TagButtonTypeSerial), @"data":serial}];
        }
    }
    if (self.post.addr) {
        [self.tagView addTag:self.post.addr type:TagButtonTypeLocation userInfo:@{@"type":@(TagButtonTypeLocation)}];
    }
    if (self.post.tags) {
        for (NSString *tag in self.post.tags) {
            [self.tagView addTag:tag type:TagButtonTypeLabel userInfo:@{@"type":@(TagButtonTypeLabel), @"data":tag}];
        }
    }
    CGSize tagViewSize = [self.tagView sizeThatFits:self.tagView.bounds.size];
    NSLayoutConstraint *heightConstraint = [self.tagView constraintForAttribute:NSLayoutAttributeHeight firstItem:self.tagView secondItem:nil];
    heightConstraint.constant = tagViewSize.height;
    NSLayoutConstraint *topConstraint = [self.tagView constraintForAttribute:NSLayoutAttributeTop firstItem:self.tagView secondItem:self.photoScrollView];
    topConstraint.constant = tagViewSize.height == 0 ? 0 : 10;
}
- (void)updateActionBarConstraint{
    NSLayoutConstraint *topConstraint = [self.contentView constraintForAttribute:NSLayoutAttributeTop firstItem:self.actionBar secondItem:self.tagView];
    topConstraint.constant = self.actionBar.hidden ? -self.actionBar.bounds.size.height : 10;
}
- (void)updateLikeDescTextViewConstraint{
    NSLayoutConstraint *topConstraint = [self.contentView constraintForAttribute:NSLayoutAttributeTop firstItem:self.likeDescTextView secondItem:self.actionBar];
    topConstraint.constant = self.likeDescTextView.hidden ? -self.likeDescTextView.bounds.size.height : 10;
}
- (void)updateCommentListViewConstraint{
    NSLayoutConstraint *topConstraint = [self.contentView constraintForAttribute:NSLayoutAttributeTop firstItem:self.commentListView secondItem:self.timeLabel];
    topConstraint.constant = self.commentListView.hidden ? -self.commentListView.bounds.size.height : 5;
}
- (void)updateCommentViewConstraint{
    NSLayoutConstraint *topConstraint = [self.contentView constraintForAttribute:NSLayoutAttributeTop firstItem:self.commentWrapperView secondItem:self.commentListView];
    topConstraint.constant = self.commentWrapperView.hidden ? -self.commentWrapperView.bounds.size.height : 5;
}
- (void)updatePhotoViewConstraint{
    CGFloat ratio = 0;
    for (NSInteger i = 0, n = self.post.items.count; i < n; i++) {
        PostItem *item = [self.post.items objectAtIndex:i];
        if (item.width > 0 && item.height > 0) {
            CGFloat r = item.height*1.0f/item.width;
            if (r > ratio) {
                ratio = r;
            }
        }
    }
    if (ratio == 0) {
        ratio = 4.0/3.0;
    }
    ratio = MIN(ratio, 4.0/3);
    NSLayoutConstraint *photoHeightConstraint = [self.photoScrollView constraintForAttribute:NSLayoutAttributeHeight firstItem:self.photoScrollView secondItem:nil];
    CGFloat h = self.bounds.size.width*ratio;
    photoHeightConstraint.constant = h;
}
- (void)setPost:(Post *)post{
    _post = post;
    self.photoScrollView.photos = [self photoItems:post];
    [self updatePhotoViewConstraint];
    self.userNameLabel.text = post.user.nickname;
    [self.userAvatarButton setImageForState:UIControlStateNormal withURL:[NSURL URLWithString:post.user.avatarThumb]];
    [self updateTagViewConstraint];
    self.contentTextView.attributedText = [CommonAttributedString contentAttributedStringWithPost:post];
//    [self.contentTextView sizeThatFits:CGSizeMake(self.contentTextView.bounds.size.width, CGFLOAT_MAX)];
    
    
    self.timeLabel.text = [post.createTime formatToHumanLang];
    [self.commentAvatarButton setImageForState:UIControlStateNormal withURL:[NSURL URLWithString:[[User currentUser] avatarThumb]] ];
    
    if (post.likeCount > 0 || post.commentCount>0) {
        self.likeDescTextView.attributedText = [CommonAttributedString commentCountAttributedStringWithPost:post];
    }
    [self updateLikeDescTextViewConstraint];
    if(post.width > 0 && post.height > 0){
        NSLayoutConstraint *photoHeightConstraint = [self.photoScrollView constraintForAttribute:NSLayoutAttributeHeight firstItem:self.photoScrollView secondItem:nil];
        CGFloat h = post.height*self.bounds.size.width/post.width;
        photoHeightConstraint.constant = h;
    }
    self.commentListView.hidden = YES;    
    [self updateCommentListViewConstraint];
}
- (IBAction)clickShareButton:(nullable id)sender{
    if (self.delegate && [self.delegate respondsToSelector:@selector(photoTableViewCellDidClickShareButton:)]) {
        [self.delegate photoTableViewCellDidClickShareButton:self];
    }
}
- (IBAction)clickLikeButton:(nullable id)sender{
    if (self.delegate && [self.delegate respondsToSelector:@selector(photoTableViewCellDidClickLikeButton:)]) {
        [self.delegate photoTableViewCellDidClickLikeButton:self];
    }
}
- (IBAction)clickFavButton:(nullable id)sender{
    if (self.delegate && [self.delegate respondsToSelector:@selector(photoTableViewCellDidClickFavButton:)]) {
        [self.delegate photoTableViewCellDidClickFavButton:self];
    }
}
- (IBAction)clickCommentButton:(nullable id)sender{
    if (self.delegate && [self.delegate respondsToSelector:@selector(photoTableViewCellDidClickCommentButton:)]) {
        [self.delegate photoTableViewCellDidClickCommentButton:self];
    }
}
- (IBAction)clickAddCommentButton:(nullable id)sender{
    if (self.delegate && [self.delegate respondsToSelector:@selector(photoTableViewCellDidClickAddCommentButton:)]) {
        [self.delegate photoTableViewCellDidClickAddCommentButton:self];
    }
}

- (IBAction)clickMenuButton:(nullable id)sender{
    if (self.delegate && [self.delegate respondsToSelector:@selector(photoTableViewCellDidClickMenuButton:)]) {
        [self.delegate photoTableViewCellDidClickMenuButton:self];
    }
}
- (IBAction)clickUserAvatarButton:(nullable id)sender{
    if (self.delegate && [self.delegate respondsToSelector:@selector(photoTableViewCellDidClickUserAvatarButton:)]) {
        [self.delegate photoTableViewCellDidClickUserAvatarButton:self];
    }
}
- (void)openLink:(NSURL *)url{
    if (self.delegate && [self.delegate respondsToSelector:@selector(photoTableViewCell:openLink:)]) {
        [self.delegate photoTableViewCell:self openLink:url];
    }
}
- (void)tagView:(TagView *)tagView didSelectButton:(UIButton *)button userInfo:(id)userInfo{
    NSInteger type = [[userInfo valueForKey:@"type"] intValue];
    if (type == TagButtonTypeSerial) {
        [self.delegate photoTableViewCell:self didSelectSerial:[userInfo valueForKey:@"data"] ofPost:self.post];
    }
    if (type == TagButtonTypeLocation) {
        [self.delegate photoTableViewCell:self didSelectLocationOfPost:self.post];
    }
    if (type == TagButtonTypeLabel) {
        [self.delegate photoTableViewCell:self didSelectTag:[userInfo valueForKey:@"data"] ofPost:self.post];
    }
}
#pragma UITextView delegate
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction{
//    if( [[URL host] isEqualToString:APP_LINK_TYPE_LIKE] ){
//        if (self.delegate && [self.delegate respondsToSelector:@selector(photoTableViewCellDidClickLikeCountView:)]) {
//            [self.delegate photoTableViewCellDidClickLikeCountView:self];
//        }
//    }
//    if( [[URL host] isEqualToString:APP_LINK_TYPE_COMMENT] ){
//        [self clickCommentButton:nil];
//    }
//    DLOG(@"%@,%@,%@",[URL scheme],[URL host],[URL lastPathComponent]);
    [self openLink:URL];
    return NO;
}
- (BOOL)textView:(UITextView *)textView shouldInteractWithTextAttachment:(NSTextAttachment *)textAttachment inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction{
    return NO;
}
//- (CGFloat)cellHeightWithPost:(Post*)post width:(CGFloat)width{
//    //from photoScrollViewbottom
//    CGFloat h = self.photoScrollView.frame.origin.y + width;
//    //addrBar height
////    h += VIEW_MARGIN+[self.tagView heightWithPost:post width:width];
//    //actionBar height
//    if (self.style == PhotoTableViewCellStyleDefault) {
//        h += VIEW_MARGIN + 32;
//    }
//    //likeDescLabel height
//    if (post.likeCount>0) {
//        h += VIEW_MARGIN + self.likeDescTextView.bounds.size.height;
//    }
//    //content height
//    h += VIEW_MARGIN + [self contentBounds:post].size.height;
//    h += VIEW_MARGIN + self.timeLabel.bounds.size.height;
//    if (self.style == PhotoTableViewCellStyleDefault) {
//        h += VIEW_MARGIN + self.commentWrapperView.bounds.size.height;
//    }
//    h += 10;
//    return h;
//}
@end
